package com.parsifal.server;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.parsifal.server.listener.OnSocketReceiveListener;
import com.parsifal.server.listener.OnSocketSendListener;
import com.parsifal.server.socket.Server;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final int REQUEST_ENABLE_BT = 1;

    private Server mServer = null;

    private BluetoothAdapter mBluetoothAdapter = null;

    private Button mBtnOpen = null;

    private Button mBtnSearch = null;

    private ListView mListView = null;

    private ProgressBar mProgressBar = null;

    private DevicesAdapter mDevicesAdapter = null;

    private ArrayList<BluetoothDevice> mDevices = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        mDevices = new ArrayList<>();
        mBtnOpen = (Button) findViewById(R.id.btn_open_bt);
        mBtnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                }
            }
        });
        mBtnSearch = (Button) findViewById(R.id.btn_search_devices);
        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgressBar.setVisibility(View.VISIBLE);
                if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    startActivity(discoverableIntent);
                }
                mBluetoothAdapter.startDiscovery();
            }
        });
        if (mBluetoothAdapter.isEnabled()) {
            mBtnSearch.setEnabled(true);
        } else {
            mBtnSearch.setEnabled(false);
        }
        mListView = (ListView) findViewById(R.id.lv_devices);
        mDevicesAdapter = new DevicesAdapter(MainActivity.this);
        mListView.setAdapter(mDevicesAdapter);
        mProgressBar = (ProgressBar) findViewById(R.id.pb_searching);
        mServer = new Server();
        mServer.setOnSendListener(new OnSocketSendListener() {
            @Override
            public void onSend(String msg) {
                Log.e(TAG, "Server onSend " + msg);
            }
        });
        mServer.setOnReceiveListener(new OnSocketReceiveListener() {
            @Override
            public void onReceive(String msg) {
                Log.e(TAG, "Server onReceive " + msg);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter searchFilter = new IntentFilter();
        searchFilter.addAction(BluetoothDevice.ACTION_FOUND);
        searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mSearchReceiver, searchFilter);

        IntentFilter stateChangeFilter = new IntentFilter();
        stateChangeFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mStateChangeReceiver, stateChangeFilter);

        IntentFilter pairingFilter = new IntentFilter();
        pairingFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mPairingReceiver, pairingFilter);

        IntentFilter pairingRequestFilter = new IntentFilter();
        pairingRequestFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(mPairingRequestReceiver, pairingRequestFilter);

        IntentFilter connectFilter = new IntentFilter();
        connectFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        connectFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(mConnectReceiver, connectFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mSearchReceiver);
        unregisterReceiver(mStateChangeReceiver);
        unregisterReceiver(mPairingReceiver);
        unregisterReceiver(mPairingRequestReceiver);
        unregisterReceiver(mConnectReceiver);
    }

    private BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BluetoothDevice.ACTION_FOUND:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (!mDevices.contains(device)) {
                        mDevices.add(device);
                    }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    if (mDevices.size() == 0) {
                        Toast.makeText(getApplicationContext(), "没有搜索到设备", Toast.LENGTH_SHORT).show();
                    } else {
                        mDevicesAdapter.fill(mDevices);
                    }
                    mProgressBar.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    };

    private BroadcastReceiver mStateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Log.e(TAG, "onReceive---------STATE_TURNING_ON");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.e(TAG, "onReceive---------STATE_ON");
                        mBtnSearch.setEnabled(true);
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.e(TAG, "onReceive---------STATE_TURNING_OFF");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Log.e(TAG, "onReceive---------STATE_OFF");
                        mBtnSearch.setEnabled(false);
                        break;
                }
            }
        }
    };

    private BroadcastReceiver mPairingReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                switch (state) {
                    case BluetoothDevice.BOND_NONE:
                        Log.d(TAG, "BOND_NONE 删除配对");
                        mDevicesAdapter.setHighLight(new ArrayList<BluetoothDevice>());
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.d(TAG, "BOND_BONDING 正在配对");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.d(TAG, "BOND_BONDED 配对成功");
                        ArrayList<BluetoothDevice> devices = new ArrayList<>();
                        devices.add(device);
                        mDevicesAdapter.setHighLight(devices);
                        break;
                }
            }
        }
    };

    private BroadcastReceiver mPairingRequestReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
                BluetoothDevice btDevice = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.i(TAG, "PairingRequestReceiver");
                abortBroadcast();
                try {
                    ClsUtils.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对
                    ClsUtils.createBond(btDevice.getClass(), btDevice);
                    ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private BroadcastReceiver mConnectReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    final BluetoothDevice device1 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d(TAG, " ACTION_ACL_CONNECTED " + device1.getName());
//                    if (isServerModel) {
//                        mBluetoothModel.connectClient(device1);
//                    } else {
//                        if (BluetoothDevice.BOND_BONDED == device1.getBondState()) {
//                            mBluetoothView.showClientDialog();
//                        }
//                    }
                    break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    final BluetoothDevice device2 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d(TAG, " ACTION_ACL_DISCONNECTED " + device2.getName());
//                    if (isServerModel) {
//                        mBluetoothModel.closeServerSocket(device2);
//                    } else {
//                        mBluetoothView.dismissClientDialog();
//                        mBluetoothModel.stopClient();
//                    }
                    break;
                default:
                    break;
            }
        }
    };
}
